package com.aishua.aishuawallet.web3jmanager;

import com.aishua.aishuawallet.Constant;

import org.web3j.protocol.Web3j;
import org.web3j.protocol.Web3jFactory;
import org.web3j.protocol.core.DefaultBlockParameterName;
import org.web3j.protocol.core.methods.response.EthGetBalance;
import org.web3j.protocol.core.methods.response.EthGetTransactionCount;
import org.web3j.protocol.core.methods.response.EthSendTransaction;
import org.web3j.protocol.http.HttpService;
import org.web3j.utils.Convert;

import java.math.BigInteger;
import java.util.concurrent.ExecutionException;

/**
 * Created by aishua on 2018/8/14.
 */

public class Web3jManager {

    private static Web3jManager web3jManager;
    private Web3j web3j;
    private Web3jManager() {

      web3j = Web3jFactory.build(new HttpService(Constant.GENTH));

    }

    public static Web3jManager getIntance() {

        if (web3jManager == null) {

            synchronized (Web3jManager.class) {

                if (web3jManager == null) {

                    web3jManager = new Web3jManager();
                }

            }
        }
        return web3jManager;
    }

     public double getBalance(String address) throws ExecutionException, InterruptedException {


         EthGetBalance ethGetBalance = web3j
                 .ethGetBalance("0x0000000000000000000000000000000000000000", DefaultBlockParameterName.LATEST)
                 .sendAsync()
                 .get();

         String wei = ethGetBalance.getBalance().toString();
         double bigDecimal = Convert.fromWei(wei, Convert.Unit.ETHER).doubleValue();

         return bigDecimal;
     }

    public String ethGetTransactionCount(String ownAddress){


        EthGetTransactionCount ethGetTransactionCount = null;
        try {

            ethGetTransactionCount = web3j.ethGetTransactionCount(ownAddress, DefaultBlockParameterName.LATEST).sendAsync().get();

        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        BigInteger nonce = ethGetTransactionCount.getTransactionCount();
        return  nonce.toString();
    }

    public String EthSendRawTransaction(String hexValue){

        //发送交易
        EthSendTransaction ethSendTransaction = null;
        String transactionHash =null;
        try {
            ethSendTransaction = web3j.ethSendRawTransaction(hexValue).sendAsync().get();
            transactionHash  = ethSendTransaction.getTransactionHash();

        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

       return transactionHash;
    }





}
